package com.security.demo.web;

import org.jasig.cas.client.util.CommonUtils;
import org.springframework.security.cas.authentication.CasAuthenticationToken;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * Created by azheng on 2017/3/14.
 */
public final class ProxyTicketSampleServlet extends HttpServlet {

    private String targetUrl;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        final CasAuthenticationToken token = (CasAuthenticationToken) request
                .getUserPrincipal();
        // proxyTicket could be reused to make calls to the CAS service even if the
        // target url differs
        final String proxyTicket = token.getAssertion().getPrincipal()
                .getProxyTicketFor(targetUrl);

        // Make a remote call to ourself. This is a bit silly, but it works well to
        // demonstrate how to use proxy tickets.
        final String serviceUrl = targetUrl + "?ticket="
                + URLEncoder.encode(proxyTicket, "UTF-8");
        String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8");

        // modify the response and write it out to inform the user that it was obtained
        // using a proxy ticket.
        proxyResponse = proxyResponse.replaceFirst("Secure Page",
                "Secure Page using a Proxy Ticket");
        proxyResponse = proxyResponse.replaceFirst("<p>", "<p>This page is rendered by "
                + getClass().getSimpleName()
                + " by making a remote call to the Secure Page using a proxy ticket ("
                + proxyTicket + ") and inserts this message. ");
        final PrintWriter writer = response.getWriter();
        writer.write(proxyResponse);
    }

    /**
     * Initialize the target URL. It allows for the host to change based upon the
     * "cas.service.host" system property. If the property is not set, the default is
     * "localhost:8443".
     */
    @Override
    public void init() throws ServletException {
        super.init();
        String casServiceHost = System.getProperty("cas.service.host", "localhost:9443");
        targetUrl = "https://" + casServiceHost + "/a/user/";
    }

    private static final long serialVersionUID = -7720161771819727775L;

}
